package fr.cephb.socialsnp.webapp.form;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class FormParam
	{
	private String name=null;
	private String label=null;
	private List<String> values=new ArrayList<String>();
	private List<Validator> validators= new ArrayList<Validator>();
	private List<ErrorMessage> errors= new ArrayList<ErrorMessage>();
	
	public FormParam(String name)
		{
		this.name=name;
		this.label=name;
		}
	
	public String getName() {
		return name;
		}
	
	public String getLabel() {
		return label;
		}
	
	public void setLabel(String label) {
		this.label = label;
		}
	
	public List<String> getValues() {
		return values;
		}
	
	public String getValue()
		{
		return getValues().isEmpty()?"":getValues().get(0).trim();
		}
	
	public List<Validator> getValidators() {
		return validators;
		}
	
	public void addValidator(Validator validator)
		{
		getValidators().add(validator);
		}
	
	public void addError(String msg)
		{
		getErrors().add(new ErrorMessage(msg));
		}
	
	public void setMaxLength(int length)
		{
		addValidator(new MaxLengthValidator(length));
		}
	
	public void setMinLength(int length)
		{
		addValidator(new MinLengthValidator(length));
		}
	
	public void setOccurence(int occurence)
		{
		setMaxOccurence(occurence);
		setMinOccurence(occurence);
		}
	
	public void setMaxOccurence(int occurence)
		{
		addValidator(new MaxOccurenceValidator(occurence));
		}
	
	public void setMinOccurence(int occurence)
		{
		addValidator(new MinOccurenceValidator(occurence));
		}
	
	public void setPattern(Pattern pattern)
		{
		addValidator(new RegexValidator(pattern));
		}
	
	public void setAllowedValues(String ...values)
		{
		Set<String> set= new HashSet<String>();
		for(String s: values) set.add(s);
		addValidator(new EnumValidator(set));
		}
	
	public List<ErrorMessage> getErrors() {
		return errors;
		}
	
	/** validate the form */
	public void validate(HttpServletRequest req)
		{
		for(String s: req.getParameterValues(getName()))
			{
			getValues().add(s);
			}
		applyValidators();
		}
	
	protected void applyValidators()
		{
		for(Validator v: getValidators())
			{
			applyValidator(v);
			}
		}
	
	protected void applyValidator(Validator v)
		{
		v.validate(this);
		}
	
	@Override
	public int hashCode() {
		return getName().hashCode();
		}
	
	@Override
	public boolean equals(Object obj) {
		return this==obj;
		}
	
	@Override
	public String toString() {
		return getName();
		}
	}
